#include "connection.h"

Connection::Connection(QObject* parent) : QTcpSocket( parent )
{
  connect(this, SIGNAL(readyRead()), this, SLOT(readIncomeData()));
  connect(this, SIGNAL(connected()), this, SLOT(doLogin()));
  connect(this, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(showState(QAbstractSocket::SocketState)));
}

void Connection::connectToServer(QString login, QString password, QString server, int port)
{
  this->login    = login;
  this->password = password;
  this->server   = server;
  this->port     = port;

  connectToHost(server, port);
}

void Connection::doLogin()
{
  qDebug() << "Logging in with login=[" << login << "] ...";
  sendCommand(login, true);
  sendCommand(password, true);
}

void Connection::showState(QAbstractSocket::SocketState state)
{
  QString result;
  qDebug() << "Socket change state to:" << state;
  switch ( state ) {

      case QAbstractSocket::UnconnectedState :
        result = "****Socket unconnected****\n";
        break;
    
      case QAbstractSocket::HostLookupState :
        result = "****Looking up server****\n";
        break;

      case QAbstractSocket::ConnectingState :
        result = "****Connecting to server****\n";
        break;

      case QAbstractSocket::ConnectedState :
        result = "****Socket connected****\n";
        break;

      case QAbstractSocket::ClosingState :
        result = "****Closing connection****\n";
        break;

      default :
       result = "****UNKNOWN socket state****\n";
  }
  emit lineReaded( result );
}

void Connection::readIncomeData()
{
  while ( bytesAvailable() > 0
          && canReadLine()
        ) {
      char buf[1024];
      int readed = readLine( buf, 1024 );
      if ( readed > 0 ) {
        QString str(buf);
        str = str.trimmed();
        qDebug() << "String readed [" << readed << "] bytes";
        emit lineReaded( str );
      }
  }
}

void Connection::sendCommand( const QString& command, bool hide )
{
  QByteArray msg = command.toUtf8() + "\n";
  write( msg );
  if ( !hide ) emit lineReaded( QString("> %1%2").arg(command).arg("\n") );
}
